<!-- User management -->
<script setup>
import { onMounted, ref } from 'vue'
import { queryAllUser, addUserApi, queryInfoApi, updateUserApi, deleteUserApi  } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { EditPen } from '@element-plus/icons-vue' 
//钩子函数 - 页面加载时触发
onMounted(() => {
  search()
})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const user = ref({
    username: '',
    nickname: '',
    gender: '',
    job: '',
    telephone: '',
    id: '',
    email: '',
    enabled: '',
})

const addUsers = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增用户'
  user.value = {
    username: '',
    nickname: '',
    gender: '',
    job: '',
    telephone: '',
    id: '',
    email: '',
    enabled: '',
  }
}

// 表单校验规则
const rules = ref({
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在2-10个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
gender: [
  { required: true, message: '请选择性别', trigger: 'change' },
  { pattern: /^[01]$/, message: '性别只能为"男"或"女"', trigger: 'blur' }
],
  job: [
    { required: true, message: '职位不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '职位长度在2-20个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
})

// 新增loading状态
const loading = ref(false);

const search = async () => {
  try {
    loading.value = true;
    console.log(`当前分页参数: pageNo=${pageNo.value}, pageSize=${pageSize.value}`);
    const result = await queryAllUser(pageNo.value, pageSize.value);
    if (result.data.code == 200 ) {
      console.log(result.data);
      userList.value = result.data.data.records;
      total.value = result.data.data.total;
    } else {
      ElMessage.error('数据加载失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  } finally {
    loading.value = false;
  }
};
const userList = ref([])
const pageNo = ref(1);
const pageSize = ref(10);
const background = ref(true)
const total = ref(0)
const handleSizeChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1;
  pageSize.value = val;
  pageNo.value = 1; // 重置到第一页
  search();
};

const handleCurrentChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1;
  if (val > Math.ceil(total.value / pageSize.value)) {
    val = Math.ceil(total.value / pageSize.value);
  }
  pageNo.value = val;
  search();
};
const save = async () => { 
  if (!userFormRef.value) return;
  userFormRef.value.validate(async (valid) => { 
    if(valid){
      let result;
      if(user.value.id)//修改
       { 
        result = await updateUserApi(user.value)
        console.log(result.data)
      }
      else//新增
      {
          result = await addUserApi(user.value)
      }
      if (result.data.code ==200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        search()
      } else {
        ElMessage.error(result.msg)
      }
    }
    else {
      ElMessage.error('数据校验失败')
    }
  })
}
const edit = async (id) => { 
  try {
    const result = await queryInfoApi(id)
    if (result.data.code ==200) {  
      dialogVisible.value = true
      dialogTitle.value = '修改用户'
      console.log(result.data)
      // 将返回的数据赋值给user对象
      user.value = result.data.data
    } else {
      ElMessage.error('获取用户信息失败：' + (result.data.message || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
};
const deleteById = async (id) => { 
  ElMessageBox.confirm(
    '你确认删除该用户吗',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
try {
  const result = await deleteUserApi(id);
  console.log(result.data); 
  if (result.data.code === 200) {
    ElMessage.success('删除成功');
    pageNo.value = 1;
    search();
  } else {
    ElMessage.error(`删除失败: ${result.data.message || '未知错误'}`);
  }
} catch (error) {
  console.error('删除请求异常:', error); // 捕获并打印错误
  ElMessage.error('删除失败，请检查网络或联系管理员');
}
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '您已取消删除',
      })
    })
};
const userFormRef = ref();


</script>

<template>
    <!-- 顶部标题 -->
    <div>
      <div id="title">用户管理</div><br>
    </div>

    
    <!-- 功能按钮 -->
    <el-button type="success" @click="addUsers">+ 新增用户信息</el-button>
    <br><br>
    
    
    <!-- 列表展示 -->
    <el-table :data="userList" border style="width: 100%" :loading="loading">
      <el-table-column prop="nickname" label="昵称" align="center" width="150px" />
      <el-table-column prop="username" label="用户名" align="center" width="150px" />
      <el-table-column 
        prop="gender" 
        label="性别" 
        align="center" 
        width="150px"
        :formatter="(row) => row.gender === 1 ? '女' : '男'"
/>
      <el-table-column prop="job" label="职位" align="center" width="150px" />
      <el-table-column prop="telephone" label="电话" align="center" width="250px"/>
      <el-table-column prop="email" label="邮箱" align="center" width="250px" ></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
          <el-button type="danger" size="small" @click="deleteById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <div class="container">
      <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>
  
  <!-- 新增/修改学员对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle"  >
    <el-form :model="user" label-width="80px" :rules="rules" ref="userFormRef"  >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="user.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-input v-model="user.job" placeholder="请输入职位" />
          </el-form-item></el-col>
          <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="user.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" :value="0" />
              <el-option label="女" :value="1" />
          </el-select>
</el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="user.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话">
            <el-input v-model="user.telephone" placeholder="请输入用户电话" />
          </el-form-item>
        </el-col>
      </el-row>


    <el-form-item>
      <el-button type="success" @click="save()">确认</el-button>
      <el-button type="primary" @click="dialogVisible = false">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>


  <!-- 违纪处理 -->

</template>



<style scoped>
#title {
  font-size: 20px;
  font-weight: 600;
  color: #e0e0e0;
}
</style>